<template>
  <div>
    <video id="video" controls></video>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import axios from 'axios'

onMounted(() => {
  document.addEventListener('DOMContentLoaded', function () {
    const video = document.getElementById('video')
    const videoUrl = '/videos/1.mp4'

    // 每次加载的片段大小（比如 1MB）
    const chunkSize = 1024 * 1024

    // 视频 mime 类型
    const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'

    if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
      const mediaSource = new MediaSource()
      video.src = URL.createObjectURL(mediaSource)

      mediaSource.addEventListener('sourceopen', () => {
        const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec)
        let start = 0

        const fetchAndAppend = () => {
          fetchVideoChunk(videoUrl, start, start + chunkSize).then((chunk) => {
            sourceBuffer.appendBuffer(chunk)
            start += chunk.byteLength

            if (chunk.byteLength < chunkSize) {
              mediaSource.endOfStream()
            }
          })
        }

        sourceBuffer.addEventListener('updateend', fetchAndAppend)
        fetchAndAppend()
      })
    } else {
      console.error('Unsupported MIME type or codec: ', mimeCodec)
    }
  })
})

const fetchVideoChunk = (url, start, end) => {
  return axios
    .get('/videos/1.mp4', {
      headers: {
        Range: `bytes=${start}-${end - 1}`,
      },
    })
    .then((response) => response.arrayBuffer())
}
</script>

<style lang="scss" scoped></style>
